# -*- coding: utf-8 -*-
# @Time : 2021/2/7 15:55
# @Author : zhangcheng
# @Software: PyCharm

from service.base_service import BaseHandler
from controller.user_controller import UserController


class UserSearchHandler(BaseHandler):
    # 查询使用GET请求，要求传入查询的autoid或name
    def get(self):
        autoid = self.get_query_argument("autoid", default=None)
        name = self.get_query_argument("name", default=None)
        if not id and not name:
            self.write({"message": "请输入查询的autoid或name字段", "error": "查询条件为空"})
            return
        else:
            kwargs = {"autoid": autoid, "name": name}
            query_result = UserController.get(**kwargs)
            self.write(query_result)


class UserCreateHandler(BaseHandler):
    # 创建使用post请求，要求传入创建用户的用户名和密码
    def post(self):
        name = self.get_body_argument("name", "")
        if name == "":
            self.write({"message": "请输入用户名", "error": "用户名为空"})
            return
        password = self.get_body_argument("password", "")
        kwargs = {"name": name, "password": password}
        result = UserController.add(**kwargs)
        self.write(result)


class UserUpdateHandler(BaseHandler):
    # 更新使用post请求，要求传入更新记录的autoid、name和password
    def post(self):
        # 通过输入的autoid来找到某条数据进行更新，只能更新name和password
        autoid = self.get_body_argument("autoid", None)
        newname = self.get_body_argument("name", None)
        newpassword = self.get_body_argument("password", None)
        if not autoid:
            self.write({"message": "请输入更新的autoid字段", "error": "autoid为空"})
            return
        kwargs = {"autoid": autoid, "name": newname, "password": newpassword}
        result = UserController.update(**kwargs)
        self.write(result)


class UserDeleteHandler(BaseHandler):
    # 删除使用GET请求，要求传入删除记录的autoid
    def get(self):
        # 通过输入的autoid来删除一条
        autoid = self.get_query_argument("autoid", None)
        if not autoid:
            self.write({"message": "请输入删除的autoid字段", "error": "autoid为空"})
            return
        else:
            kwarg = {"autoid": autoid}
            result = UserController.delete(**kwarg)
            self.write(result)
